import { Image } from '@tarojs/components'
import { encode as btoa } from 'base-64'
import { renderToString } from 'react-dom/server'

const Svg = ({ children, ...props }) => {
  let htmlString = renderToString(children)

  // 如果没有xmlns，自动加一个
  if (htmlString && !htmlString.includes('xmlns')) {
    htmlString = htmlString.replace(/viewBox="(.*?)"/g, (match) => `${match} xmlns="http://www.w3.org/2000/svg" `)
  }

  return htmlString && <Image {...props} src={`data:image/svg+xml;base64,${btoa(htmlString)}`} />
}

export default Svg
